﻿
Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService

Partial Class Control_HolidayCalendar_List
    Inherits System.Web.UI.UserControl
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

#Region "Sub and Function"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            If Not Request.QueryString("Calendarid") Is Nothing Then
                hidIDEdit.Value = Request.QueryString("Calendarid")
                ShowData()
            End If
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If

            BindddlYear()
            BindToGrid(1, ddlYearSearch.SelectedValue)
            btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
        End If
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, Optional ByVal strSearch As String = "")
        Using data As New VSEntities
            'So ban ghi muon the hien tren trang
            strSearch = ddlYearSearch.SelectedValue
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim p As List(Of VSModel.HolidayCalendar)
            Dim h As Integer
            If strSearch <> "" AndAlso strSearch <> 0 Then

                Dim FromYear = StringToDate("01/01/" & ddlYearSearch.SelectedValue)
                Dim ToYear = StringToDate("31/12/" & ddlYearSearch.SelectedValue)

                p = (From q In data.HolidayCalendars Where q.Date >= FromYear AndAlso q.Date <= ToYear Order By q.Date Select q).Skip((iPage - 1) * intPag_Size).Take(intPag_Size).ToList
                h = (From q In data.HolidayCalendars Where q.Date >= FromYear AndAlso q.Date <= ToYear Order By q.Date Select q.CalendarId).Count
            Else
                p = (From q In data.HolidayCalendars Order By q.Date Select q).Skip((iPage - 1) * intPag_Size).Take(intPag_Size).ToList
                h = (From q In data.HolidayCalendars Order By q.Date Select q.CalendarId).Count
            End If

            Dim strKey_Name() As String = {"CalendarId", "Date"}
            'Tong so ban ghi

            'Tong so ban ghi
            If h > 0 Then
                hidCount.Value = h
                Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If


            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
            btnDelete.CausesValidation = False
            hidDel.Value = "0"
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
        If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
            ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
        Else
            Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
        End If

        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        BindToGrid(lnkTile.ToolTip)
        ResetForm()
        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region
#Region "Event for control"

    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("CalendarId").ToString
            Dim q = (From p In data.Holidaycalendars Where p.CalendarId = intId Select p).FirstOrDefault
            Try
                strLogName = q.Date
                data.HolidayCalendars.DeleteObject(q)
                data.SaveChanges()
                Insert_App_Log("Delete HolidayCalendar:" & strLogName & "", Function_Name.HolidayCalendar, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)

                'dang ky lai ajax
                Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
                If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                    ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
                Else
                    Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
                End If

            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()

    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Using data As New VSEntities
            Try
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        intTotal += 1
                        Dim strLogName As String
                        intId = grdShow.DataKeys(item.RowIndex)("CalendarId").ToString
                        Dim q = (From p In data.Holidaycalendars Where p.CalendarId = intId Select p).FirstOrDefault
                        Try
                            strLogName = q.Date
                            data.HolidayCalendars.DeleteObject(q)
                            data.SaveChanges()
                            Insert_App_Log("Delete HolidayCalendar:" & strLogName & "", Function_Name.HolidayCalendar, Audit_Type.Delete, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                            intCount += 1

                        Catch ex As Exception
                        End Try
                    End If
                Next
                If intCount > 0 Then
                    Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');;window.location ='../../Page/Holidaycalendar/List.aspx';", Me.Page, True)
                Else
                    Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1

            Dim lblDate As Label = CType(e.Row.FindControl("lblDate"), Label)
            '  hplDate.NavigateUrl = "../../Page/Holidaycalendar/Detail.aspx?Calendarid=" & grdShow.DataKeys(e.Row.RowIndex)("CalendarId").ToString
            Dim CovertDate As DateTime = grdShow.DataKeys(e.Row.RowIndex)("Date").ToString
            lblDate.Text = CovertDate.ToString("dd/MM/yyyy")
            Dim lblDateOfWeek As Label = CType(e.Row.FindControl("lblDateOfWeek"), Label)
            lblDateOfWeek.Text = arrDayOfWeek(CovertDate.DayOfWeek.GetHashCode)

            Dim chkItem As CheckBox = CType(e.Row.FindControl("chkItem"), CheckBox)
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            If CovertDate >= Now.Date Then
                lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
                hplEdit.NavigateUrl = "../../Page/Holidaycalendar/List.aspx?Calendarid=" & grdShow.DataKeys(e.Row.RowIndex)("CalendarId").ToString
            Else
                lnkbtnDelete.Enabled = False
                hplEdit.Enabled = False
                chkItem.Enabled = False
            End If
        End If
    End Sub
#End Region

#Region "Event for control "
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim date2check As Date = StringToDate(txtDate.Text.Trim)
        Using data As New VSEntities

            If hidIDEdit.Value = 0 Then
                'kiểm tra dữ liệu trùng

                Dim p As New VSModel.HolidayCalendar
                Dim k As HolidayCalendar = (From q In data.HolidayCalendars Where q.Date = date2check Select q).FirstOrDefault
                If Not k Is Nothing Then
                    Excute_Javascript("Alertbox('Ngày này đã có trong hệ thống');", Me.Page, True)
                    Exit Sub
                End If
                Try
                    p.Date = date2check
                    p.Note = txtNote.Text.Trim()
                    data.HolidayCalendars.AddObject(p)
                    data.SaveChanges()
                    Insert_App_Log("Insert HolidayCalendar:" & txtDate.Text.Trim & "", Function_Name.HolidayCalendar, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');", Me.Page, True)
                    ResetForm()
                    BindToGrid()

                Catch ex As Exception
                    log4net.Config.XmlConfigurator.Configure()
                    log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                    Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/Holidaycalendar/List.aspx';", Me.Page, True)
                End Try
            Else
                Dim k As HolidayCalendar = (From q In data.HolidayCalendars Where q.Date = date2check And q.CalendarId <> hidIDEdit.Value Select q).FirstOrDefault
                If Not k Is Nothing Then
                    Excute_Javascript("Alertbox('Ngày này đã có trong hệ thống');", Me.Page, True)
                    Exit Sub
                End If

                Dim p As HolidayCalendar = (From q In data.HolidayCalendars Where q.CalendarId = hidIDEdit.Value).SingleOrDefault
                Try
                    p.CalendarId = hidIDEdit.Value
                    p.Date = date2check
                    p.Note = txtNote.Text.Trim()
                    data.SaveChanges()
                    Insert_App_Log("Update HolidayCalendar:" & txtDate.Text.Trim() & "", Function_Name.HolidayCalendar, Audit_Type.Edit, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');", Me.Page, True)
                    ResetForm()
                    BindToGrid()

                Catch ex As Exception
                    log4net.Config.XmlConfigurator.Configure()
                    log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                    Excute_Javascript("Alertbox('Cập nhật thất bại.');window.location ='../../Page/Holidaycalendar/List.aspx';", Me.Page, True)
                End Try
            End If

        End Using
    End Sub
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub
    Protected Sub ShowData()
        Using data As New VSEntities
            Dim p As HolidayCalendar = (From q In data.HolidayCalendars Where q.CalendarId = hidIDEdit.Value Select q).SingleOrDefault
            If Not p Is Nothing Then
                Dim CovertDate As DateTime = p.Date.ToString
                txtDate.Text = CovertDate.ToString("dd/MM/yyyy")
                txtNote.Text = IIf(IsNothing(p.Note) = True, "", p.Note)
            End If
        End Using
    End Sub
#End Region


    Protected Sub ddlYearSearch_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlYearSearch.SelectedIndexChanged
        BindToGrid(1, ddlYearSearch.SelectedValue.Trim())
    End Sub

    Public Sub BindddlYear()
        Dim dt = Enumerable.Range(Now.Year - 1, 3)
        With ddlYearSearch
            .DataSource = dt
            .DataBind()
        End With
        ddlYearSearch.Items.Insert(0, New ListItem("--- Tất cả ---", "0"))
        ddlYearSearch.SelectedValue = Now.Year
    End Sub

    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        If grdShow.Rows.Count > 0 Then
            BindToGrid(1, ddlYearSearch.SelectedValue.Trim())
        End If
    End Sub
    Protected Sub ResetForm()
        txtDate.Text = ""
        txtNote.Text = ""

    End Sub

    Protected Sub btnSatSunGen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSatSunGen.Click
        If ddlYearSearch.SelectedValue = "0" Then
            Excute_Javascript("Alertbox('Hãy chọn năm tương ứng để tạo ngày nghỉ');window.location ='../../Page/Holidaycalendar/List.aspx';", Me.Page, True)
            Exit Sub
        End If
        Dim FromDate = StringToDate("01/01/" & ddlYearSearch.SelectedValue)
        Dim ToDate = StringToDate("31/12/" & ddlYearSearch.SelectedValue)
        Using data As New VSEntities
            While FromDate <= ToDate

                Dim k As HolidayCalendar = (From q In data.HolidayCalendars Where q.Date = FromDate Select q).FirstOrDefault
                If k Is Nothing Then
                    '0: CN, 1: MON, ... 6:SAT
                    Dim listDateOff = (From anh In data.SYS_PARAMETERS Where anh.Name.Contains("DATE_OF_WEEK_OFF") Select anh.Val).FirstOrDefault()

                    If Not listDateOff Is Nothing Then
                        'Dim tem = listDateOff.Split(";")
                        If listDateOff.ToUpper.Contains(FromDate.DayOfWeek.ToString.ToUpper()) Then
                            Dim p As New VSModel.HolidayCalendar
                            p.Date = FromDate
                            p.Note = txtNote.Text.Trim()
                            data.HolidayCalendars.AddObject(p)
                            data.SaveChanges()
                        End If
                    End If
                End If
                FromDate = FromDate.AddDays(1)
            End While
        End Using
        BindToGrid(1, ddlYearSearch.SelectedValue)
    End Sub
End Class

